package com.common.account.service;

import com.common.basis.entity.User;
import com.common.basis.exception.BusinessException;
import com.common.basis.util.AESUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Map;
import java.util.Objects;

/**
 * 密码-验证码登录
 *
 * @author wangguochao
 */
@Service
@Slf4j
@AllArgsConstructor
public class PawVerifyService {

    private final IAuUserService iAuUserService;
    private final StringRedisTemplate stringRedisTemplate;
    private final BCryptPasswordEncoder passwordEncoder;
    /**
     * 安全配置
     */
    private final SecurityProperties securityProperties;

    /**
     * 验证码登录
     */
    public UserDetails loadUserByPawAndVerify(Map<String, String> param) {
        String key = param.get("key");
        String verify = param.get("verify");
        String username = param.get("username");
        String password = param.get("password");
        password = AESUtil.aesDecrypt(password, "C64EC4C5AEBDEC29FB2B3628C7FBA57E");
        log.error(password);
        SecurityProperties.User propertiesUser = securityProperties.getUser();
        User user = new User();
        if (propertiesUser != null && username.equals(propertiesUser.getName()) && Objects.equals(password, propertiesUser.getPassword())) {
            user.setPassword(propertiesUser.getPassword());
            user.setUsername(propertiesUser.getName());
            user.setAuthorities(new HashSet<>());
            user.setTenantId("system");
            user.setUserId(propertiesUser.getName());
            user.setAccountNonExpired(true);
            user.setAccountNonLocked(true);
            user.setCredentialsNonExpired(true);
            user.setEnabled(true);
        } else {
            user = iAuUserService.getUserByName(username);
            //没有openid
            if (user == null) {
                throw new BusinessException("用户名或密码错误！");
            }
            if (!passwordEncoder.matches(password, user.getPassword())) {
                throw new BusinessException("用户名或密码错误！");
            }
        }
        String verifyByKey = stringRedisTemplate.opsForValue().get(key);
        //忽略大小写
        verify = verify.toUpperCase();
        if (verifyByKey == null || !verifyByKey.equals(verify)) {
            throw new BusinessException("验证码无效");
        }

        //设置权限
//        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), user.getAuthorities());
        return user;
    }
}
